const express = require('express');
const { body } = require('express-validator');
const authController = require('../controllers/authController');
const { protect, optionalAuth } = require('../middleware/auth');
const rateLimit = require('express-rate-limit');

const router = express.Router();

// 限制认证相关请求的频率
const authLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15分钟
  max: 5, // 限制每个IP 15分钟内最多5次请求
  message: {
    status: 'error',
    message: '请求过于频繁，请稍后再试'
  },
  standardHeaders: true,
  legacyHeaders: false
});

// 限制密码重置请求的频率
const passwordResetLimiter = rateLimit({
  windowMs: 60 * 60 * 1000, // 1小时
  max: 3, // 限制每个IP 1小时内最多3次密码重置请求
  message: {
    status: 'error',
    message: '密码重置请求过于频繁，请1小时后再试'
  },
  standardHeaders: true,
  legacyHeaders: false
});

// 验证规则
const signupValidation = [
  body('username')
    .isLength({ min: 3, max: 30 })
    .withMessage('用户名长度必须在3-30个字符之间')
    .matches(/^[a-zA-Z0-9_]+$/)
    .withMessage('用户名只能包含字母、数字和下划线'),
  
  body('email')
    .isEmail()
    .withMessage('请提供有效的邮箱地址')
    .normalizeEmail(),
  
  body('phone')
    .isMobilePhone('zh-CN')
    .withMessage('请提供有效的手机号码'),
  
  body('password')
    .isLength({ min: 8 })
    .withMessage('密码长度至少8个字符')
    .matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]/)
    .withMessage('密码必须包含至少一个大写字母、一个小写字母、一个数字和一个特殊字符'),
  
  body('firstName')
    .isLength({ min: 1, max: 50 })
    .withMessage('名字长度必须在1-50个字符之间')
    .trim(),
  
  body('lastName')
    .isLength({ min: 1, max: 50 })
    .withMessage('姓氏长度必须在1-50个字符之间')
    .trim(),
  
  body('dateOfBirth')
    .optional()
    .isISO8601()
    .withMessage('请提供有效的出生日期'),
  
  body('gender')
    .optional()
    .isIn(['male', 'female', 'other'])
    .withMessage('性别必须是 male、female 或 other')
];

const loginValidation = [
  body('identifier')
    .notEmpty()
    .withMessage('请提供邮箱、手机号或用户名'),
  
  body('password')
    .notEmpty()
    .withMessage('请提供密码')
];

const forgotPasswordValidation = [
  body('email')
    .isEmail()
    .withMessage('请提供有效的邮箱地址')
    .normalizeEmail()
];

const resetPasswordValidation = [
  body('password')
    .isLength({ min: 8 })
    .withMessage('密码长度至少8个字符')
    .matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]/)
    .withMessage('密码必须包含至少一个大写字母、一个小写字母、一个数字和一个特殊字符'),
  
  body('passwordConfirm')
    .notEmpty()
    .withMessage('请确认密码')
];

const updatePasswordValidation = [
  body('currentPassword')
    .notEmpty()
    .withMessage('请提供当前密码'),
  
  body('newPassword')
    .isLength({ min: 8 })
    .withMessage('新密码长度至少8个字符')
    .matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]/)
    .withMessage('新密码必须包含至少一个大写字母、一个小写字母、一个数字和一个特殊字符'),
  
  body('newPasswordConfirm')
    .notEmpty()
    .withMessage('请确认新密码')
];

// 公开路由（无需认证）

/**
 * @route   POST /api/auth/signup
 * @desc    用户注册
 * @access  Public
 */
router.post('/signup', authLimiter, signupValidation, authController.signup);

/**
 * @route   POST /api/auth/login
 * @desc    用户登录
 * @access  Public
 */
router.post('/login', authLimiter, loginValidation, authController.login);

/**
 * @route   POST /api/auth/logout
 * @desc    用户登出
 * @access  Public
 */
router.post('/logout', authController.logout);

/**
 * @route   POST /api/auth/refresh-token
 * @desc    刷新访问令牌
 * @access  Public
 */
router.post('/refresh-token', authController.refreshToken);

/**
 * @route   POST /api/auth/forgot-password
 * @desc    忘记密码
 * @access  Public
 */
router.post('/forgot-password', passwordResetLimiter, forgotPasswordValidation, authController.forgotPassword);

/**
 * @route   PATCH /api/auth/reset-password/:token
 * @desc    重置密码
 * @access  Public
 */
router.patch('/reset-password/:token', resetPasswordValidation, authController.resetPassword);

/**
 * @route   GET /api/auth/verify-email/:token
 * @desc    验证邮箱
 * @access  Public
 */
router.get('/verify-email/:token', authController.verifyEmail);

/**
 * @route   GET /api/auth/check
 * @desc    检查认证状态
 * @access  Public
 */
router.get('/check', optionalAuth, authController.checkAuth);

/**
 * @route   POST /api/auth/wechat-phone-login
 * @desc    微信小程序手机号登录/注册
 * @access  Public
 */
router.post('/wechat-phone-login', [
  body('phone')
    .isMobilePhone('zh-CN')
    .withMessage('请提供有效的手机号码')
], authController.wechatPhoneLogin);

// 受保护的路由（需要认证）

/**
 * @route   PATCH /api/auth/update-password
 * @desc    更新密码
 * @access  Private
 */
router.patch('/update-password', protect, updatePasswordValidation, authController.updatePassword);

/**
 * @route   GET /api/auth/me
 * @desc    获取当前用户信息
 * @access  Private
 */
router.get('/me', protect, authController.getMe);

/**
 * @route   POST /api/auth/resend-verification
 * @desc    重新发送验证邮件
 * @access  Private
 */
router.post('/resend-verification', protect, authController.resendVerificationEmail);

module.exports = router;